<template>
    <div style=" background-image: url(http://localhost:8888/cover/0439bd6424c84d088135dfecc75a1fb7);">
      <el-container style="width: 80%;margin: 0px auto;">
        <!-- 头部 -->
        <el-header>
          <h1 style="color: gray;">{{user.username != ''?user.username:'张三'}}的个人博客</h1>
        </el-header>
        
        <div>
            <img style=" object-fit: cover;height: 100px;width: 1024px;" src="http://localhost:8888/cover/e57fc6e84dcd42d7b68798301f1bc46b" alt="" srcset="">
        </div>
        <!-- 主体内容 -->
        <el-main>
          <!-- 用户信息 -->
          <el-card style="display:flex;flex-direction: column;">
            <!-- <div slot="header" class="clearfix">
              <span>个人信息</span>
            </div> -->
            <div style="display: flex; flex: 1;overflow: hidden;">
              <el-avatar :src="user.picture" :size="100" style="display: flex;align-self: center;"></el-avatar>
              <div style="display: flex;align-items: center;margin: 15px 0px 0px 15px;">
                <el-descriptions title="个人信息:" border>
                  <template #extra>
                    <div style="display: flex;flex-direction: column;align-items: start;justify-content: space-between;padding: 0px 10px;">
                      <div>
                          <h2>
                            {{ user.username }}
                            <el-button v-if="this.$store.state.user.u_id != this.user.u_id" type="primary" size="small" :disabled="relation" :plain="relation" round @click="buildRelation(user.u_id)">
                              {{ relation?'已关注':'关注' }}
                            </el-button>
                          </h2>
                      </div>
                    </div>
                  </template>
                  <el-descriptions-item label-align="left" label="总访问量：" :align="left">{{ views }} 次</el-descriptions-item>
                  <el-descriptions-item label-align="left" label="最多查看：" :align="left">{{ maxView }} 次</el-descriptions-item>
                  <el-descriptions-item label-align="left" label="粉丝：" :align="left">{{ fans }} 人</el-descriptions-item>
                  <el-descriptions-item label-align="left" label="个人简介:" :align="left">
                    <el-text v-if="this.$store.state.user.u_id != this.user.u_id" line-clamp="2" style="width: 500px;">
                      {{ user.status }}
                    </el-text>
                    <el-input v-else-if="this.$store.state.user.u_id == this.user.u_id" v-model="user.status" @blur="changeUserStatus" placeholder="Please input"/>
                  </el-descriptions-item>
                </el-descriptions>
              </div>
            </div>
          </el-card>

          <!-- 信息设置 -->
          <test4 v-if="this.$store.state.user.u_id == this.user.u_id"></test4>
          
          <!-- 文章列表 -->
          <el-card>
            <div slot="header" class="clearfix">
              <span>文章列表</span>

              <span style="float: right; padding: 3px 0">共{{ articles.length }}篇</span>
            </div>
            <el-row>
              <el-col :span="8" v-for="post in articles.slice(0,maxShow)" :key="post.id">
                <el-card class="article" shadow="hover" style="position: relative;">
                  <el-icon @click="edit(post),initialization()" class="edit" v-if="this.$store.state.user.u_id == this.user.u_id" :size="30" style="position: absolute;right: 10px;top: 10px;"><Edit /></el-icon>
                  <img :src="post.cover" class="post-cover" alt="cover" width="60px">

                  <h3>{{ post.title }}</h3>
                  <p>{{ post.description }}</p>
                  <div style="display: flex;justify-content: center;">
                      <el-button type="primary" @click="showArticle(post.a_id)">阅读详情</el-button>
                  </div>
                  <el-text line-clamp="1" style="float: right;">{{ post.date }}</el-text>
                </el-card>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-button v-if="maxShow<this.articles.length" type="text" @click="exibitionArticle">加载更多<el-icon><ArrowDownBold /></el-icon></el-button>
                <el-button v-else type="text" @click="this.maxShow = 3">已经是全部了<el-icon><ArrowUpBold /></el-icon></el-button>
              </el-col>
            </el-row>
          </el-card>
        </el-main>
      </el-container>
    </div>

    <!-- 修改帖子 -->
    <el-dialog v-model="dialogFormVisible" title="修改帖子">
      <el-form :model="form">
        <el-form-item label="帖子名称" :label-width="formLabelWidth">
          <el-input v-model="form.title" autocomplete="off" />
        </el-form-item>
        <el-form-item label="封面" :label-width="formLabelWidth">
          <el-upload action="" :http-request="upload" :on-success="successUpload">
            <el-image :src="form.cover" style="height: 70px;"></el-image>
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="简介" :label-width="formLabelWidth">
          <el-input v-model="form.description" autocomplete="off" />
        </el-form-item>
        <el-form-item label="可选标签" :label-width="formLabelWidth">
          <el-select
            v-model="form.tags"
            multiple
            collapse-tags
            placeholder="Select"
            style="width: 240px"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="修改文章" :label-width="formLabelWidth">
          <div id="editor" style="width: 100%;">

          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="dialogFormVisible = false,publish()">
            修改
          </el-button>
        </span>
      </template>
    </el-dialog>

</template>

<script>
import E from "wangeditor"
import axios from 'axios';
import { ElMessage } from 'element-plus'
import { ElNotification } from 'element-plus'
import test4 from '@/components/AdminComponents/test4.vue';

let editor 
function initWangEditor(content){setTimeout(()=>{
  if(!editor){
    editor= new E("#editor")
    editor.config.placeholder="请输入内容"
    editor.config.uploadFileName='file'
    editor.config.uploadImgAccept = []
    editor.config.uploadImgServer = 'http://localhost:8888/files/wang/upload'
    editor.create()
  }
  editor.txt.html(content)
},0)
}
export default {
  name: 'Mine',
  components: {test4},
  props: {},
  data() {
    return {
      content:'',
      maxShow:3,
      relation:false, 
      user: {
        
      },
      fans:0,
      maxView:0,
      views:0,
      articles: [
        
      ],
      //发帖参数
      form:{
          title: '',
          description: '',
          tags:[],
          content:'',
          cover:''
        },
        dialogTableVisible: false,
        dialogFormVisible : false,
        formLabelWidth : '140px',
        options : this.$store.state.tags
    };
  },
  computed: {},
  watch: {},
  methods: {
    edit(article){
      this.form=article
      // console.log(this.form);
      //如果收到传入的数据，更改为前端自己需要的类型
      if(JSON.stringify(this.form.tags) != '[]'){  
        this.form.tags = article.tags.split(",")
      }
      this.dialogFormVisible=true
    },
    initialization(){
      initWangEditor(this.form.content)
    },
    publish(){    //存入后端
      //author,author_gravatar, author_id, title, description,tags,content,cover
      this.form.author=this.user.username  /** author **/
      this.form.author_gravatar=this.user.picture  /** author_gravatar **/
      this.form.author_id=this.user.u_id   /** author_id **/
      this.form.title=this.form.title  /** title **/
      this.form.description=this.form.description  /** description **/
      if (this.form.tags.length > 0) {     /** tags **/
        this.form.tags = this.form.tags.join(',') //转换为后端存入需要的字符串
      }else{
        this.form.tags = ''
      }
      this.form.content=editor.txt.html()  /** content **/
      this.form.cover=this.form.cover      /** cover **/
      this.form
      const url = 'http://localhost:8888/article/change'
      axios.post(url,JSON.parse(JSON.stringify(this.form)),{header:{'Content-Type': 'application/json'}}).then( data =>{
        ElMessage({
          message: '修改成功.',
          type: 'success',
        })
        ElNotification({
          title: '您的作品已经修改',
          message: "相关信息请在个人页面查看",
        })
        console.log(JSON.parse(JSON.stringify(this.form)));
        this.formInit()  // 重新初始化表单
      }).catch(Response=>{
        ElMessage.error('上传失败.')
      })
    },
    upload(param){  //上传封面
      const formData = new FormData();
      formData.append('file', param.file);
      const url = 'http://localhost:8888/cover/coverUpload'
      axios.post(url, formData).then( data =>{
        ElMessage({
          message: '上传成功.',
          type: 'success',
        })
        this.form.cover=data.data.data[0].url
        console.log(this.form.cover);
      }).catch(Response=>{
        ElMessage.error('上传失败.')
      })
    },
    formInit(){
      this.form ={
          author:'',
          author_id:'',
          title: '',
          description: '',
          tags:[],
          content:'',
          cover:''
      }
    },
    changeUserStatus(){
      axios.get("http://localhost:8888/user/changeUserStatus",{
        params:{
          u_id:this.user.u_id,
          userStatus:this.user.status
        }
      }).then(data=>{
        ElMessage({
          // showClose: true,
          message: '已修改个人简介.',
          type: 'success',
        })
      })
    },
    exibitionArticle(){
      if(this.articles.length > 3){
        this.maxShow = this.articles.length+1
      }else{
        ElMessage({
          // showClose: true,
          message: '已经是全部了.',
          type: 'warning',
        })
      }
    },
    showArticle(id){
      this.$router.push({path:'/article',query:{id:id}})
    },
    getUserInfo(){      //获取用户信息
      axios.get("http://localhost:8888/user/getUserInfo",{
        params:{
          u_id:this.$route.query.id
        }
      }).then(data=>{
        if(data.data.data){
          let res = data.data.data 
          this.user =res.user
          //如果user为空
          if(this.user == null){
            this.$router.push("/error")
            return
          }
          this.articles = res.articles
          this.maxView = res.maxView
          this.views = res.views
          this.fans = res.fans
        }else{
          this.$router.push("/error")
        }
        
      }).catch(err=>{
        this.$router.push("/error")
      })
    },
    isRelation(){       //是否已经关注过
      if(this.$store.state.user.u_id === null || this.$route.query.id === null) return
      axios.get('http://localhost:8888/user/isRelation',{
        params:{
          focus_id:this.$store.state.user.u_id,
          focused_id:this.$route.query.id
        }
      }).then(data=>{
        console.log('isRelation:'+data.data.data);
        if(data.data.data){
          this.relation = true
        }else{
          this.relation = false
        }
      })
    },
    buildRelation(id){    //如果没有关注，则关注
      console.log(this.user.u_id);
      if(id === this.$store.state.user.u_id){
        ElMessage({
          // showClose: true,
          message: '你不能关注自己.',
          type: 'warning',
        })
        return
      }
      if(this.$store.state.user.u_id === null || this.user.u_id === null) return
      axios.get('http://localhost:8888/user/buildRelationship',{
        params:{
          focus_id:this.$store.state.user.u_id,
          focused_id:this.user.u_id
        }
      }).then(data=>{
        if(data.data.data){
          ElMessage({
            // showClose: true,
            message: '关注成功.',
            type: 'success',
          })
          this.relation = true
        }else{
          ElMessage({
            // showClose: true,
            message: '请勿重复关注.',
            type: 'error',
          })
          // this.relation = true
        }
      })
    },
    init(){
      this.getUserInfo()
      this.isRelation()
    }
  },
  created() {
    this.init()
  },
  mounted() {}
}
</script>

<style scoped>
.edit :hover{
  color: coral;
}
.post-cover {
 width: 100%;
 height: 150px;
 object-fit: cover;
}

.clearfix {
 display: flex;
 justify-content: space-between;
}

.article{
  margin: 5px;
  /* padding: 5px; */
}

.article:hover{
  box-shadow: 0 0 10px rgba(0,0,0,0.5);
  cursor: pointer;
}

:deep(.el-form-item__label){
  justify-content: flex-start;
}

.pb{
  border-radius: 20px;
  border: none;
}
.pb:hover{
  background-color: #fff !important;
  color: #fc5531 !important;
}

</style>
